package com.crane.api.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crane.api.config.DeviceConfig;
import com.crane.api.dto.DeviceInfo;
import com.crane.api.dto.UpLoadRopeData;
import com.crane.common.core.dto.Response;
import com.crane.common.core.dto.SingleResponse;
import com.crane.common.core.utils.CollectionUtil;
import com.crane.common.core.utils.StringUtil;
import com.crane.common.framework.utils.DateUtil;
import com.crane.common.framework.utils.Jackson2JsonUtil;
import com.crane.oss.school.bean.request.task.EndTaskRopeReq;
import com.crane.oss.school.bean.resp.TaskStudentSkipRopeResp;
import com.crane.oss.school.dao.*;
import com.crane.oss.school.model.*;
import com.crane.oss.school.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zx
 * @Date: 2022/11/10/9:20
 * @Description:
 */
@RestController
@RequestMapping("/device")
public class AppDeviceController {

    @Resource
    protected HttpServletRequest httpServletRequest;

    @Resource
    protected HttpServletResponse httpServletResponse;

    @Resource
    DeviceConfig deviceConfig;

    @Resource
    protected StudentEquipmentDao studentEquipmentDao;

    @Resource
    StudentSkipropeDao studentSkipropeDao;

    @Resource
    EquipmentDao equipmentDao;

    @Resource
    StudentDao studentDao;

    @Resource
    TaskStudentDao taskStudentDao;

    @Resource
    TaskService taskService;

    private static final Logger logger = LoggerFactory.getLogger(AppDeviceController.class);

    @RequestMapping(value = "/getbaseinfo", method = RequestMethod.GET)
    public Map getBaseInfo(String imei) {
        logger.info("getBaseInfo imei={}", imei);
        Map<String, Object> result = new HashMap<>();
        Equipment dbEquipment=equipmentDao.selectOne(Wrappers.lambdaQuery(Equipment.class).eq(Equipment ::getImei,imei));
        if(null == dbEquipment){
            result.put("errno", "90003");
            result.put("errmsg", "设备不存在");
            httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
            return result;
        }
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setName(dbEquipment.getName());
        deviceInfo.setHttpserver(deviceConfig.getHttpserver());
        deviceInfo.setMqttserver(deviceConfig.getMqttserver());
        deviceInfo.setMusicmode(dbEquipment.getMusicMode());
        deviceInfo.setSkipmode(dbEquipment.getSkipmode());
        deviceInfo.setImsi(dbEquipment.getImsi());
        deviceInfo.setImei(imei);
        deviceInfo.setProduct_type("S8");
        deviceInfo.setFw_version("");
        deviceInfo.setSystime(System.currentTimeMillis());

        Long studentId=null;
        List<StudentEquipment> studentEquipmentList=studentEquipmentDao.selectList(Wrappers.lambdaQuery(StudentEquipment.class)
                .eq(StudentEquipment ::getEquipmentId,dbEquipment.getEquipmentId()));

        if(CollectionUtil.isNotEmpty(studentEquipmentList)){
            for(StudentEquipment studentEquipment : studentEquipmentList){
                if(studentEquipment.getBindStatus().equals(1) && studentEquipment.getBindType().equals(1)){
                    studentId=studentEquipment.getStudentId();
                    break;
                }
            }
        }
        if(null == studentId){
            deviceInfo.setIs_bind(0);
            result.put("errno", "90000");
            result.put("errmsg", "success");
            result.put("data", deviceInfo);
            httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
            return result;
        }

        Student student=studentDao.selectById(studentId);
        if(null == student || null == student.getHeight() || null == student.getWeight()){
            result.put("errno", "90003");
            result.put("errmsg", "学生资料不全");
            httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
            return result;
        }
        deviceInfo.setHeight(student.getHeight().toString());
        deviceInfo.setWeight(student.getWeight().toString());
        deviceInfo.setIs_bind(1);
        result.put("errno", "90000");
        result.put("errmsg", "success");
        result.put("data", deviceInfo);
        httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
        return result;
    }

    @RequestMapping(value = "/dataupload", method = RequestMethod.POST)
    public Map dataUpload(@RequestBody UpLoadRopeData ropeData) {
        Map<String, Object> result = new HashMap<>();
        //0 skipdata,1 设备imei,2 设备imsi,3 本机号码,4 网络类型,5 产品型号,6 固件版本号,7 电池电量,8 当前音乐模式,9 场景id,10 跳绳模式,11 开始时间,12 结束时间,13 跳绳个数,14 当前卡路里消耗
        //skipdata,866834034871083,460110411841070,null,LTE,S8,S8_V1.0_20221030,12,3,1,1667092354,1667092414,134,12
        logger.info("dataupload skipdata={}", Jackson2JsonUtil.toString(ropeData));
        String[] datas=ropeData.getSkipdata().split(",");
        String imei=datas[0];
        Integer quantity=Integer.valueOf(datas[12]);
        Date beginTime=new Date(Long.parseLong(datas[10]) * 1000);
        Date endTime=new Date(Long.parseLong(datas[11]) * 1000);
        Integer duration=Math.toIntExact(Long.parseLong(datas[11]) - Long.parseLong(datas[10]));
        Double frequency= null;
        if(quantity != 0){
            frequency=new BigDecimal(quantity).multiply(new BigDecimal(60)).divide(new BigDecimal(duration),2, RoundingMode.HALF_UP).doubleValue();
        }
        Double kcal=Double.valueOf(datas[13]);
        Long taskStudentId=null;
        if(StringUtil.isNotBlank(datas[8])){
            taskStudentId = Long.valueOf(datas[8]);
        }
        Integer model=Integer.valueOf(datas[9]);

        Equipment dbEquipment=equipmentDao.selectOne(Wrappers.lambdaQuery(Equipment.class).eq(Equipment ::getImei,imei));
        if(null == dbEquipment){
            result.put("errno", "90003");
            result.put("errmsg", "设备不存在");
            httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
            return result;
        }
        dbEquipment.setImsi(datas[1]);
        dbEquipment.setNetwork(datas[3]);
        dbEquipment.setModel(datas[4]);
        dbEquipment.setVersion(datas[5]);
        equipmentDao.updateById(dbEquipment);

        Long studentId=null;
        List<StudentEquipment> studentEquipmentList=studentEquipmentDao.selectList(Wrappers.lambdaQuery(StudentEquipment.class)
                .eq(StudentEquipment ::getEquipmentId,dbEquipment.getEquipmentId()));

        if(CollectionUtil.isNotEmpty(studentEquipmentList)){
            for(StudentEquipment studentEquipment : studentEquipmentList){
                if(studentEquipment.getBindStatus().equals(1) && studentEquipment.getBindType().equals(1)){
                    studentId=studentEquipment.getStudentId();
                    break;
                }
            }
        }
        if(null == studentId){
            result.put("errno", "90003");
            result.put("errmsg", "未绑定学生");
            httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
            return result;
        }

        Equipment equipment=equipmentDao.selectOne(Wrappers.lambdaQuery(Equipment.class).eq(Equipment ::getEquipmentId,dbEquipment.getEquipmentId()));
        if(null == equipment || equipment.getStatus().equals(2)){
            result.put("errno", "90003");
            result.put("errmsg", "设备不可用");
            httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
            return result;
        }
        TaskStudent taskStudent = null;
        if (null != taskStudentId && taskStudentId.intValue() != 0 ) {
            taskStudent=taskStudentDao.selectById(taskStudentId);
            if (null == taskStudent) {
                result.put("errno", "90003");
                result.put("errmsg", "无开始打卡记录");
                httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
                return result;
            }
        }

        StudentSkiprope studentSkiprope = new StudentSkiprope();
        studentSkiprope.setStudentId(studentId);
        studentSkiprope.setEquipmentId(dbEquipment.getEquipmentId());
        studentSkiprope.setModel(model);
        studentSkiprope.setQuantity(quantity);
        studentSkiprope.setFrequency(frequency);
        studentSkiprope.setKcal(kcal);
        studentSkiprope.setBeginTime(beginTime);
        studentSkiprope.setEndTime(endTime);
        studentSkiprope.setDuration(duration);
        studentSkiprope.setUpdateTime(new Date());
        if (null ==taskStudent ) {
            studentSkiprope.setType(2);
            studentSkiprope.setStatus(2);
            studentSkiprope.setCreateTime(new Date());
            studentSkipropeDao.insert(studentSkiprope);
        } else {
            StudentSkiprope dbStudentSkiprope = studentSkipropeDao.selectById(taskStudent.getRelationId());
            dbStudentSkiprope.setStatus(1);
            dbStudentSkiprope.setModel(model);
            dbStudentSkiprope.setQuantity(quantity);
            dbStudentSkiprope.setFrequency(frequency);
            dbStudentSkiprope.setKcal(kcal);
            dbStudentSkiprope.setBeginTime(beginTime);
            dbStudentSkiprope.setEndTime(endTime);
            dbStudentSkiprope.setDuration(duration);
            dbStudentSkiprope.setUpdateTime(new Date());
            studentSkipropeDao.updateById(dbStudentSkiprope);
        }
        result.put("errno", "90000");
        result.put("errmsg", "success");
        httpServletResponse.setContentLength(Jackson2JsonUtil.toString(result).getBytes(StandardCharsets.UTF_8).length);
        return result;
    }

}
